package com.yonyou.gmcc.gateway.web.filter;

import java.net.InetAddress;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.connector.Request;
import org.apache.tomcat.util.http.MimeHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.gmcc.gateway.web.consts.CommonConstants;
import com.yonyou.gmcc.gateway.web.util.ReflectionUtils;
import com.yonyou.gmcc.gateway.web.util.TokenCheck;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

@Service
public class AccessFilter extends ZuulFilter  {

    private static Logger log = LoggerFactory.getLogger(AccessFilter.class);
    
    @Override
	public Object run() {
    	log.info("------进入gateway------");
    	RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        HttpServletResponse res = ctx.getResponse();
        if(!TokenCheck.check(request, res)) {
            log.warn("---access token not pass");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(505);
            return null;
        }

//        ctx.getResponse().addHeader("Access-Control-Allow-Credentials", "true");
//        ctx.getResponse().addHeader("Access-Control-Allow-Origin", "*");
//        ctx.getResponse().addHeader("Access-Control-Allow-Methods", "OPTIONS,HEAD,GET,PUT,POST,DELETE,PATCH");
		return null;
	}
    

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 获取登录用户远程主机ip地址
     * 
     * @param request
     * @return
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}